<?php
/**
 * Created by PhpStorm.
 * User: 80053521
 * Date: 2015/1/13
 * Time: 15:05
 */

namespace fbi\helpers;


class Tools {
	/**
	 * @return string
	 */
	public static function getUserIp(){
		switch (true) {
			case isset($_SERVER["HTTP_X_FORWARDED_FOR"]):
				$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
				break;
			case isset($_SERVER["HTTP_CLIENT_IP"]):
				$ip = $_SERVER["HTTP_CLIENT_IP"];
				break;
			default:
				$ip = $_SERVER["REMOTE_ADDR"] ? $_SERVER["REMOTE_ADDR"] : '127.0.0.1';
		}
		if (strpos($ip, ', ') > 0) {
			$ips = explode(', ', $ip);
			$ip = $ips[0];
		}
		return $ip;
	}

	/**
	 * @return int
	 */
	public static function getUserPort(){
		return isset($_SERVER['REMOTE_PORT'])?$_SERVER['REMOTE_PORT']:0;
	}



	/**
	 * 将数组转化为xml对象
	 * @param array $data
	 * @param string $root root element
	 * @param SimpleXMLElement $xml
	 * @param string $unknown
	 * @param string $doctype xml document type
	 * @return SimpleXMLElement
	 */
	public static function array2xml(array $data, $root = 'data', $xml = NULL, $unknown = 'element', $doctype = "<?xml version = '1.0' encoding = 'utf-8'?>")
	{
		if(is_null($xml)) {
			$xml = simplexml_load_string("$doctype<$root/>");
		}

		foreach ($data as $k => $v) {
			if (is_int($k)) {
				$k = $unknown;
			}

			if (is_scalar($v)) {
				$xml->addChild($k, $v);
			} else {
				self::array2xml((array)$v, $k, $xml->addChild($k));
			}
		}

		return $xml;
	}

	/**
	 * PB类,转为数组
	 * @param PBMessage $pb
	 */
	public static function PB2Array(PBMessage $pb){
		$clsName = get_class($pb);
		$methods = get_class_methods($clsName);
		$return = array();
		foreach($methods as $method){
			if( strpos($method,'set_')===0 ){
				$property = substr($method,4);
				if( in_array('remove_last_'.$property, $methods) ){//repeated
					$propsize="{$property}_size";
					$return[$property.'_size']=$pb->$propsize();
					for($i=0;$i<$return[$property.'_size'];$i++){
						$pbs = $pb->$property($i);
						$return[$property][]=self::PB2Array($pbs);
					}
				}else{//single
					if($pb->$property()){
						$return[$property]=$pb->$property();
					}
				}
			}
		}
		return $return;
	}

} 